<?php
namespace Core\Db\Feature;


use Core\Session\AdminSessionHelper;
use Core\Session\ApplicationSessionHelper;
use Core\Session\FrontSessionHelper;
use Exception;
use Zend\Db\Sql\Insert;
use Zend\Db\TableGateway\Feature\AbstractFeature;
use Zend\Di\ServiceLocator;

class InjectMetaFieldFeature extends AbstractFeature
{

    /**
     * @var ServiceLocator
     */
    protected $serviceLocator;


    /**
     * @param \Zend\Di\ServiceLocator $serviceLocator
     */
    public function setServiceLocator($serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
    }

    /**
     * @return \Zend\Di\ServiceLocator
     */
    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }



    public function preInsert(Insert $insert){
        $allColumns = $this->tableGateway->columns;
        if(in_array('created_by',$allColumns)){
            if(ApplicationSessionHelper::getCurrentModule() == 'admin')
                $insert->created_by = AdminSessionHelper::getUser()->id ;
            elseif(ApplicationSessionHelper::getCurrentModule() == 'front'
                || ApplicationSessionHelper::getCurrentModule() == 'ad_restaurant')
                $insert->created_by = FrontSessionHelper::getUser()->id ;
        }

        $isContainedLang = true;
        try{
           $tmp = $insert->lang;
        }catch (Exception $e){
            $isContainedLang = false;
        }

        if(in_array('lang',$allColumns) && !$isContainedLang ){
            if(ApplicationSessionHelper::getCurrentModule() == 'admin')
                $insert->lang = AdminSessionHelper::getCurrentLang() ;
            elseif(ApplicationSessionHelper::getCurrentModule() == 'front')
                $insert->lang = FrontSessionHelper::getCurrentLang() ;
            elseif(ApplicationSessionHelper::getCurrentModule() == 'ad_restaurant')
                $insert->lang = FrontSessionHelper::getCurrentLang() ;
        }

    }

}